import { Dispatch, SetStateAction, useCallback, useState } from "react"
import useUnmountedRef from "./useUnmountedRef.ts"

function useSafeState<S>(initialState: S): [S, Dispatch<SetStateAction<S>>]

function useSafeState<S = undefined>(): [
  S | undefined,
  Dispatch<SetStateAction<S | undefined>>
]

/**
 * 安全管理状态，防止组件卸载后更新状态
 * @param initialState 初始值
 * @returns
 */
function useSafeState<S>(initialState?: S | (() => S)) {
  const unmountedRef: { current: boolean } = useUnmountedRef()
  const [state, setState] = useState(initialState)

  const setCurrentState = useCallback((currentState: S | (() => S)) => {
    if (unmountedRef.current) return
    setState(currentState)
  }, [])

  return [state, setCurrentState] as const
}

export default useSafeState
